﻿namespace Digitalmes.Application.Mes;

/// <summary>
/// 生产任务服务
/// </summary>
[ApiExplorerSettings(GroupName = "mes")]
public sealed class ProdTaskService : IDynamicWebApiService
{
    private readonly SugarRepository<ProdTask> _taskRepo;
    private readonly SugarRepository<MdShift> _shiftRepo;

    public ProdTaskService(SugarRepository<ProdTask> taskRepo, SugarRepository<MdShift> shiftRepo)
    {
        _taskRepo = taskRepo;
        _shiftRepo = shiftRepo;
    }

    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ProdTaskDto>> GetPagesAsync(PageParam param)
    {
        var query = await _taskRepo.AsQueryable()
            .Includes(m => m.Shift)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ProdTaskDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ProdTaskDto> GetAsync(long id)
    {
        var model = await _taskRepo.GetByIdAsync(id);
        return model.Adapt<ProdTaskDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(ProdTaskDto model)
    {
        var task = model.Adapt<ProdTask>();
        if (await _taskRepo.IsAnyAsync(s => s.LineId == model.LineId && s.ShiftId == task.ShiftId && s.Area == task.Area))
        {
            Oops.ThrowBah(ErrCode.E4003);
        }

        return await _taskRepo.InsertAsync(task);
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(ProdTaskDto model)
    {
        var task = model.Adapt<ProdTask>();
        if (await _taskRepo.IsAnyAsync(s => s.LineId == model.LineId && s.ShiftId == task.ShiftId && s.Area == task.Area && s.Id != task.Id))
        {
            Oops.ThrowBah(ErrCode.E4003);
        }

        return await _taskRepo.UpdateAsync(task, m => new 
        {
            m.TailProcCode,
            m.Qty,
            m.UpdateTime,
            m.UpdateUser,
        });
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody] long id) =>
        await _taskRepo.DeleteAsync(m => m.Id == id);
}
